//
//  ESTActivityViewController.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/9/29.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "ESTActivityViewController.h"
#import "ESTActivityTableViewCell.h"
#import "ESTActivityHomeModel.h"
#import "ESTActivityModel.h"
#import "ESTLoginTool.h"
#import "ESTActivityAchieveController.h"
#import "ESTActivityListViewController.h"
#import "ESTActivityDetailViewController.h"
#import "ESTActivityChartsViewController.h"
#import "ESTFollowModeViewController.h"
#import "ESTActivitySearchViewController.h"
#import "ESTFollowUpRecordViewController.h"
#import "TYZCallPhoneTool.h"
@interface ESTActivityViewController ()<UITableViewDelegate, UITableViewDataSource>
/**
 *  TableView
 */
@property(nonatomic, strong) TYZTableView *tableView;
/**
 *  记录滑动量
 */
@property(nonatomic, assign) CGFloat offSetY;
/**
 *  所有的活动
 */
@property(nonatomic, strong) NSArray<ESTActivityModel *> *activityData;
/**
 *  选择了第几个
 */
@property(nonatomic, assign) NSInteger activityInteger;
/**
 *  选择的日周月
 */
@property(nonatomic, assign) NSInteger dateType;
/**
 *  对应的活动数据模型
 */
@property(nonatomic, strong) ESTActivityHomeModel *model;
/**
 *  开始时间
 */
@property(nonatomic, copy) NSString *startDate;
/**
 *  结束时间
 */
@property(nonatomic, copy) NSString *endDate;
/**
 *  当天
 */
@property(nonatomic, copy) NSString *currentDate;
/**
 *  记录偏移量
 */
@property(nonatomic, assign) CGPoint lastContentOffset;
/**
 *  通话时长的模型
 */
@property(nonatomic, strong) TYZCallPhoneModel *callModel;
@end

@implementation ESTActivityViewController
#pragma mark - 生命周期方法
- (void)viewDidLoad {
    [super viewDidLoad];
    CoreInfo.scrmType = SCRM_TYPE_ACTIVITY;
    [self setupTitleView];
    [self setupTableView];
    self.dateType = 1;
    self.callModel = [TYZCallPhoneModel readModelInSendbox];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self refreshHomeData];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)setupTitleView {
    TYZView *titleView = [[TYZView alloc] init];
    [self.view addSubview:titleView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(DE_NavigationHeight);
    }];
    titleView.backgroundColor = NavigationColor;
    TYZLabel *nameLabel = [[TYZLabel alloc] init];
    [titleView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(titleView).offset(-10);
        make.centerX.equalTo(titleView);
    }];
    nameLabel.text = [@"最新活动" S];
    nameLabel.textColor = TYZWhiteColor;
    nameLabel.font = [UIFont boldSystemFontOfSize:CoreInfo.fontSize * 1.2];
    
    TYZButton *leftButton = [[TYZButton alloc] init];
    [titleView addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleView).offset(20);
        make.centerY.equalTo(nameLabel);
    }];
    [leftButton setImage:[UIImage imageNamed:@"na_exit"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(didClickExitButton) forControlEvents:UIControlEventTouchUpInside];
    
    TYZButton *addButton = [[TYZButton alloc] init];
    [titleView addSubview:addButton];
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameLabel);
        make.right.equalTo(titleView).offset(-20);
    }];
    [addButton setBackgroundImage:[UIImage imageNamed:@"na_add"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(didClickAddButton) forControlEvents:UIControlEventTouchUpInside];
    
    TYZButton *searchButton = [[TYZButton alloc] init];
    [titleView addSubview:searchButton];
    [searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameLabel);
        make.right.equalTo(addButton.mas_left).offset(-10);
    }];
    [searchButton setBackgroundImage:[UIImage imageNamed:@"search_icon"] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(didClickSearchButton) forControlEvents:UIControlEventTouchUpInside];
}
- (void)refreshHomeData {
    [self acquireActivity];
}
- (void)acquireActivity {
    WEAKSELF
    [TYZLoadingView showMessage:nil];
    [ESTActivityModel requestAllActivitySuccess:^(NSArray<ESTActivityModel *> *modelArray) {
        weakSelf.activityData = modelArray;
    } failure:^(NSString *error) {
        weakSelf.activityData = nil;
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
- (void)acquireData {
    WEAKSELF
    [ESTActivityHomeModel requestActivityHomeDataWithActivityID:self.activityData[self.activityInteger].ACTIVITY_ID startDate:self.startDate endDate:self.endDate success:^(ESTActivityHomeModel *model) {
        [TYZLoadingView hideHUD];
        weakSelf.model = model;
        [weakSelf refreshTableView];
        [weakSelf.tableView.mj_header endRefreshing];
    } failure:^(NSString *error) {
        [weakSelf refreshTableView];
        [weakSelf.tableView.mj_header endRefreshing];
        [TYZLoadingView showError:error];
    }];
}
- (void)refreshTableView {
//    self.lastContentOffset = self.tableView.contentOffset;
    [self.tableView reloadData];
//    self.tableView.contentOffset = self.lastContentOffset;
}
- (void)setupTableView {
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(DE_NavigationHeight);
    }];
    [self setupTableViewMj_header];
}
- (void)setupTableViewMj_header {
    WEAKSELF
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [weakSelf refreshHomeData];
    }];
    MJRefreshStateHeader *stateHeader = (MJRefreshStateHeader *)self.tableView.mj_header;
    stateHeader.textColor = TYZWhiteColor;
}
#pragma mark - actions
- (void)didClickExitButton {
    CoreInfo.scrmType = SCRM_TYPE_ASSISTANT;
#ifdef ACTIVITY
    WEAKSELF
    [TYZSystemDialog dialogWithTitle:[@"退出当前账号？" S] complement:^{
        [TYZLoadingView showMessage:nil];
        [ESTLoginTool logoutWithComplement:^(BOOL result) {
            [TYZLoadingView hideHUD];
            if (result) {
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }
        }];
    }];
#else
    if (UserInfo.login_user_type == USER_TYPE_ACTIVITY_COMMISSIONER) {
        WEAKSELF
        [TYZSystemDialog dialogWithTitle:[@"退出当前账号？" S] complement:^{
            [TYZLoadingView showMessage:nil];
            [ESTLoginTool logoutWithComplement:^(BOOL result) {
                [TYZLoadingView hideHUD];
                if (result) {
                    [weakSelf dismissViewControllerAnimated:YES completion:nil];
                }
            }];
        }];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
#endif
}
- (void)didClickAddButton {
    if (self.activityData.count > 0) {
        ESTFollowUpRecordViewController *controller = [[ESTFollowUpRecordViewController alloc] init];
        controller.followUpType = FollowUpRecordType_Add;
        controller.activity_id = self.activityData[self.activityInteger].ACTIVITY_ID;
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        [TYZLoadingView showNormal:[@"当前没有活动" S]];
    }
}
- (void)didClickSearchButton {
    ESTActivitySearchViewController *controller = [[ESTActivitySearchViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)handleLastCallInfo {
    // 读取到有上次通话未跟进的时长信息
    if (self.callModel) {
        if ([self.callModel.user_id isEqualToString:UserInfo.userid]) {
            if ([self.activityData[self.activityInteger].ACTIVITY_ID isEqualToString:self.callModel.activity_id]) {
                WEAKSELF
                [TYZSystemDialog dialogWithTitle:[@"上次通话结束尚未跟进\n是否立即跟进？" S] complement:^{
                    ESTFollowUpRecordViewController *controller = [[ESTFollowUpRecordViewController alloc] init];
                    controller.callModel = weakSelf.callModel;
                    controller.followUpType = FollowUpRecordType_Senbox;
                    controller.custom_id = weakSelf.callModel.custom_id;
                    controller.activity_id = weakSelf.callModel.activity_id;
                    controller.duration = weakSelf.callModel.dailTime;
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                    weakSelf.callModel = nil;
                }];
            }
        } else {
            // 清理数据
            self.callModel = nil;
            [TYZCallPhoneModel deleteModelInSendBox];
        }
    }
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 320;
    } else if (indexPath.section == 1) {
        return 120;
    } else if (indexPath.section == 2) {
        return 200;
    } else if (indexPath.section == 3) {
        return 120;
    }
    return 44;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3 || section == 0) {
        return 0;
    }
    return Value_Height_PartPadding;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    TYZView *view = [[TYZView alloc] init];
    view.backgroundColor = ESTBackgroundColor;
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ESTActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ESTActivityTableViewCell"];
    WEAKSELF
    switch (indexPath.section) {
        case 0:
        {
            cell = [ESTActivityTableViewCell activityAchieveCellWithActivityData:self.activityData activityInteger:self.activityInteger dateType:self.dateType dataModel:self.model];
            [cell setDidClickChooseActivityBlock:^(NSArray<NSNumber *> *numberArray) {
                weakSelf.activityInteger = [numberArray.lastObject integerValue];
                [weakSelf acquireData];
                [weakSelf handleLastCallInfo];
            }];
            [cell setDidClickDayWeekMonthBlock:^(NSInteger integer) {
                weakSelf.dateType = integer;
                [weakSelf refreshHomeData];
            }];
            [cell setDidClickMyAchieveBlock:^(NSInteger integer) {
                if (weakSelf.activityData.count > 0) {
                    ESTActivityAchieveController *controller = [[ESTActivityAchieveController alloc] init];
                    controller.item = integer;
                    controller.dateType = weakSelf.dateType;
                    controller.activity_id = weakSelf.activityData[weakSelf.activityInteger].ACTIVITY_ID;
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                } else {
                    [TYZLoadingView showNormal:[@"当前没有活动" S]];
                }
            }];
        }
            break;
        case 1:
        {
            cell = [ESTActivityTableViewCell activityMatterCellWithDataModel:self.model];
            [cell setDidClickMatterBlock:^(NSInteger integer) {
                if (weakSelf.activityData.count > 0) {
                    ESTFollowModeViewController *controller = [[ESTFollowModeViewController alloc] init];
                    controller.mode = integer;
                    controller.activity_id = weakSelf.activityData[weakSelf.activityInteger].ACTIVITY_ID;
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                } else {
                    [TYZLoadingView showNormal:[@"当前没有活动" S]];
                }
            }];
        }
            break;
        case 2:
        {
            cell = [ESTActivityTableViewCell activityReportCellWithDataModel:self.model];
            [cell setDidClickChartsBlock:^{
                if (weakSelf.activityData.count > 0) {
                    ESTActivityChartsViewController *controller = [[ESTActivityChartsViewController alloc] init];
                    controller.modelArray = weakSelf.activityData;
                    controller.number = weakSelf.activityInteger;
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                } else {
                    [TYZLoadingView showNormal:[@"当前没有活动" S]];
                }
            }];
        }
            break;
        case 3:
        {
            ESTActivityModel *model = self.activityData.count > 0 ? self.activityData[self.activityInteger] : nil;
            cell = [ESTActivityTableViewCell activityContentCellWithActivityModel:model];
            [cell setDidClickMoreActivityBlock:^{
                if (weakSelf.activityData.count > 0) {
                    ESTActivityListViewController *controller = [[ESTActivityListViewController alloc] init];
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                } else {
                    [TYZLoadingView showNormal:[@"当前没有活动" S]];
                }
            }];
            [cell setDidClickActivityDetailBlock:^(NSInteger integer) {
                if (weakSelf.activityData.count > 0) {
                    ESTActivityDetailViewController *controller = [[ESTActivityDetailViewController alloc] init];
                    controller.activity_id = weakSelf.activityData[weakSelf.activityInteger].ACTIVITY_ID;
                    [weakSelf.navigationController pushViewController:controller animated:YES];
                } else {
                    [TYZLoadingView showNormal:[@"当前没有活动" S]];
                }
            }];
        }
            break;
        default:
            break;
    }
    return cell;
}
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offSetY = scrollView.contentOffset.y;
    self.offSetY = offSetY;
    if (offSetY < 0 && self.offSetY > 0) {
        self.offSetY = offSetY;
    }
    if (offSetY >= 0 && self.offSetY < 0) {
        self.offSetY = offSetY;
    }
}
#pragma mark - setter & getter
- (TYZTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TYZTableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)setOffSetY:(CGFloat)offSetY {
    _offSetY = offSetY;
    if (offSetY <= 0) {
        self.tableView.backgroundColor = NavigationColor;
    } else {
        self.tableView.backgroundColor = TYZWhiteColor;
    }
}
- (void)setDateType:(NSInteger)dateType {
    _dateType = dateType;
    switch (dateType) {
        case 0:
            self.startDate = self.currentDate;
            self.endDate = self.currentDate;
            break;
        case 1: {
            NSArray *arr = [TYZTool weekTypeDayArrayWithDateString:self.currentDate];
            self.startDate = arr.firstObject;
            self.endDate = arr.lastObject;
        }
            break;
        case 2:{
            NSArray *arr = [TYZTool monthTypeDayArrayWithDateString:self.currentDate];
            self.startDate = arr.firstObject;
            self.endDate = arr.lastObject;
        }
            break;
        default:
            break;
    }
}
- (void)setActivityData:(NSArray<ESTActivityModel *> *)activityData {
    _activityData = activityData;
    if (activityData.count > 0) {
        [self handleLastCallInfo];
        [self acquireData];
    } else {
        [self.tableView.mj_header endRefreshing];
        [TYZLoadingView hideHUD];
    }
}
- (NSString *)currentDate {
    return [[NSDate date] formatterDate:@"yyyy-MM-dd"];
}
@end

